<?php

namespace app\api\model\service;

use think\Model;
use think\Db;
use think\Exception;
use traits\model\SoftDelete;
class Skill extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'service_skill';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';


    /**
     * 查询附近技师
     * @param $get
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function nearSkill($get)
    {
        $lng = $get['lng'];
        $lat = $get['lat'];
        $orderBy = 'distance asc';
        $earth = 6378.137;
        $pi = 3.1415926535898;
        $list = self::where(['city' => $get['city'], 'state' => 1, 'is_rest' => 0, 'accept_nums' => ['>', 0]])
            ->field("id,user_id,name,goods_ids,user_image,image,city,age,level,(2*$earth*ASIN(SQRT(POW(SIN($pi*(" . $lat . "-lat)/360),2)+COS($pi*" . $lat . "/180)*COS(lat*$pi/180)*POW(SIN($pi*(" . $lng . "-lng)/360),2)))) as distance")
            ->order($orderBy)
            ->page($get['page'])
            ->limit($get['limit'])
            ->select();
        return $list;
    }


    /**
     * 查询服务人员列表
     * @param $get
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function searchSkill($get)
    {
        extract($get);
        $lng = $get['lng'];
        $lat = $get['lat'];
        $orderBy = 'distance asc';
        $earth = 6378.137;
        $pi = 3.1415926535898;
        $where['state'] = 1;
        $where['accept_nums'] = ['>', 0];
        if (isset($name) && $name != '') {
            $where['name'] = ['like', "%$name%"];
        }
        if (isset($city) && $city != '') {
            $where['city'] = $city;
        }
        if (isset($category_id) && $category_id != '') {
            $where['category_id'] = $category_id;
        }
        if (isset($skill_cate_id) && $skill_cate_id != '') {
            $where['skill_cate_id'] = $skill_cate_id;
        }
        if (isset($goods_id) && $goods_id != '') {
            $where[] = ['exp', Db::raw("FIND_IN_SET('$goods_id',goods_ids)")];
        }
        if (isset($shop_id) && $shop_id != '') {
            $where['shop_id'] = $shop_id;
        }
        if (isset($product_id) && $product_id != '') {
            $two_category_id = model('\app\api\model\service\Goods')->where(['id'=>$product_id])->value('two_category_id');
            $where[] = ['exp', Db::raw("FIND_IN_SET('$two_category_id',goods_ids)")];
        }
        
        $list = self::where($where)
            ->field("id,user_id,name,skill_cate_id,shop_id,user_image,image,is_rest,city,age,level,(2*$earth*ASIN(SQRT(POW(SIN($pi*(" . $lat . "-lat)/360),2)+COS($pi*" . $lat . "/180)*COS(lat*$pi/180)*POW(SIN($pi*(" . $lng . "-lng)/360),2)))) as distance")
            ->order($orderBy)
            ->page($get['page'])
            ->limit($get['limit'])
            ->select();
        // return self::getLastSql();
        return $list;
    }

    public static function getCount($params)
    {
        $params['state'] = 1;
        return self::where($params)->count();
    }


    public static function skillInfo($id)
    {
        return self::where(['id' => $id])->field('id,user_id,name,shop_id,sex,age,images,goods_ids,mobile,image,edu,nation,height,weight,exper,lng,lat,is_rest,front_image,certificate_image,health_image')->find();

    }

    public static function getOrderSkill($skill_id)
    {
        return self::where(['id' => $skill_id])->field('id,image,name,mobile')->find();
    }

    public static function getSkillScore($skill_id)
    {
        $data['average_score'] = Comment::getCommentScore(['skill_id' => $skill_id]);
        $data['good_comment_percent'] = Comment::skillGoodPercent(['skill_id' => $skill_id]);
        return $data;
    }


    /**
     * 服务人员详情
     * @param $id
     * @param $uid
     * @return array|bool|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getInfo($id, $uid)
    {
        $info = db('service_skill')->where(['id' => $id])->field('id,user_id,name,shop_id,city,sex,age,image,images,goods_ids,edu,nation,exper,lng,lat,is_rest,front_image,certificate_image,health_image')->find();
        if (!$info['id']) {
            return false;
        }
        
        if($info['shop_id'] != ''){
            // return $info['shop_id'];
            $info['goodsList'] = \app\api\model\service\Goods::where(['two_category_id'=>['in',$info['goods_ids']],'status'=>'normal','shop_id'=>$info['shop_id'],'city'=>$info['city'],'shop_state'=>1])->order('weigh desc')->select();// 条件加上 'shop_state'=>1
        }else{
            $info['goodsList'] = \app\api\model\service\Goods::where(['two_category_id'=>['in',$info['goods_ids']],'status'=>'normal','shop_id'=>0,'city'=>$info['city'],'shop_state'=>1])->order('weigh desc')->select();// 条件加上 'shop_state'=>1
        }
        
        $info['followState'] = $uid ? Follow::getState(['follow_id' => $id, 'user_id' => $uid,'type' => 0]) : 0;
        $info['images'] = $info['images']?explode(',', $info['images']):'';
        $info['shopname'] = $info['shop_id'] ? Shop::getName($info['shop_id']) : '';
        return $info;
    }


    public static function getSkillInfo($params)
    {
        $skill = self::where(['id' => $params['id'], 'state' => 1])->field('id,name,shop_id,image,skill_cate_id,age,lng,lat,is_rest')->find();
        if (!$skill) {
            return false;
        }
        $skill['skillCate'] = SkillCate::getName($skill['skill_cate_id']);
        $skill['average_score'] = Comment::getCommentScore(['skill_id' => $skill['id']]);
        $skill['skillTime'] = SkillTime::getSkillTime($skill['id']);
        $skill['shopname'] = $skill['shop_id'] ? Shop::getName($skill['shop_id']) : '';
        $skill['distance'] = \addons\service\library\Common::distance($params['lng'], $params['lat'], $skill['lng'], $skill['lat']);
        $skill['commentCount'] = Comment::getCount(['skill_id' => $skill['id'], 'state' => 1]);
        $skill['good_comment_percent'] = Comment::skillGoodPercent(['skill_id' => $skill['id']]);
        return $skill;
    }


    /**
     * 获得服务者商户
     * @param $uid
     * @return array|bool|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getSkillShop($uid)
    {
        $info = self::where(['user_id' => $uid])->field('id,name,shop_id,code')->find();
        $info['shopInfo'] = $info['shop_id'] ? Shop::getShop($info['shop_id']) : '';
        return $info;
    }


    public static function getShopSkill($params,$page)
    {
        // return $params;
        $list = Skill::where($params)->field('id,ensure_price,image,percent,name,sex,city,district,address,lng,lat')->order('id desc')->page($page)->limit(10)->select();
        foreach ($list as $key=>$value)
        {
            $list[$key]['orderCount'] = Order::getOrderCount(['skill_id'=>$value['id'],'status'=>['in',[2,3,4]]]);
            $list[$key]['orderList'] = Order::getOrder(['skill_id'=>$value['id'],'status'=>['in',[2,3,4]]]);
            $list[$key]['average_score'] = Comment::getCommentScore(['skill_id' => $value['id']]);
            $list[$key]['good_comment_percent'] = Comment::skillGoodPercent(['skill_id' => $value['id']]);
        }
        return $list;
    }




    public static function getShopSkillList($params,$page)
    {
        $list = Skill::where($params)->field('id,ensure_price,image,percent,name,sex,city,district,address,lng,lat,user_id,is_rest')->order('id desc')->page($page)->limit(10)->select();
        foreach ($list as $key=>$value)
        {
            $list[$key]['skillDetail'] = self::skillShopDetail(['id'=>$value['id'],'shop_id'=>$params['shop_id'],'user_id'=>$value['user_id']]);
        }
        return $list;
    }

    public static function skillShopDetail($params)
    {
        $data = [];
        $data['average_score'] = Comment::getCommentScore(['skill_id' => $params['id']]);
        $data['shopMoney'] = UserInfo::where(['user_id'=>$params['user_id']])->value('shop_money');
        $data['orderCount'] = Order::getOrderCount(['skill_id'=>$params['id'],'shop_id'=>$params['shop_id'],'is_settle'=>2]);
        $data['orderPrice'] = Order::getOrderPrice(['skill_id'=>$params['id'],'shop_id'=>$params['shop_id'],'is_settle'=>2],'settle_price');
        $data['withdrawPrice'] = Withdraw::where(['user_id'=>$params['user_id'],'shop_id'=>$params['shop_id'],'state'=>2])->sum('num');
        $data['notServiceCount'] = Order::getOrderCount(['skill_id'=>$params['id'],'shop_id'=>$params['shop_id'],'status'=>['in',[2,3,4,5]],'is_service'=>['in',[0,-1]]]);
        $data['notSettleCount'] = Order::getOrderCount(['skill_id'=>$params['id'],'shop_id'=>$params['shop_id'],'is_settle'=>1]);
        return $data;
    }





    /**
     * 检测服务人员可接单状态
     * @param $id
     * @return array|bool|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function checkAcceptState($id,$goods_id)
    {
        $info = self::where(['id'=>$id,'state'=>1,'is_rest'=>0])->field('id,name,goods_ids,accept_nums')->find();
        if(!$info)
        {
            throw new Exception('当前服务者无法接单');
        }
        
        // 由于客户修改逻辑直接查询goods_id查不到数据，需要用two_category_id 去查询
        $two_category_id = \app\api\model\service\Goods::where(['id'=>$goods_id])->value('two_category_id');
        if(!in_array($two_category_id,explode(',',$info['goods_ids']))){
            throw new Exception('当前服务者无此服务项目');
        }
        return $info;
    }


    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $skill = self::where('user_id',$user_id)->lock(true)->find();
            if ($skill && $money != 0) {
                $before = $skill->ensure_price;
                $after = function_exists('bcadd') ? bcadd($skill->ensure_price, $money, 2) : $skill->ensure_price + $money;
                //更新会员信息
                $skill->save(['ensure_price' => $after]);
                //写入日志
                EnsureLog::create(['user_id' => $user_id, 'money' => $money, 'type'=>0, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }
}